<template>
  <!-- 设置用户基本信息 -->
  <view class="settings">
    <view class="avator">
      <view class="inner" @tap="startImage">
        <img src="../../static/img/avator.svg" alt="" />
        <m-icon class="scan" type="camera"></m-icon>
      </view>
      <!-- <picker @change="bindPickerChange" :value="index" :range="array">
        <view class="uni-input">{{array[index]}}</view>
      </picker> -->
    </view>
    <view class="content">
      <uni-forms v-model="formData" ref="form" validateTrigger="bind" :rules="rules" @submit="submit">
        <uni-forms-item label="真实姓名" name="username" labelWidth="85">
          <input placeholder="请输入真实姓名" :value="formData.username" @blur="binddata('username', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="证件类型" name="idType" labelWidth="85">
          <picker
            @change="handleListChange($event, 'idType', idTypeList, 'id')"
            :value="idTypeList.findIndex(e => e.id === formData.idType)"
            range-key="label"
            :range="idTypeList"
          >
            <view class="inner">
              <text :class="{'uni-input': true, 'placeholder': !idTypeListMap[formData.idType]}">{{ idTypeListMap[formData.idType] || '请选择证件类型'}}</text>
            </view>  
          </picker>
        </uni-forms-item>
        <uni-forms-item label="证件号码" name="idCard" labelWidth="85">
          <input placeholder="请输入证件号码" :value="formData.idCard" @blur="binddata('idCard', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="联系电话" name="phone" labelWidth="85">
          <input placeholder="请输入联系电话" :value="formData.phone" @blur="binddata('phone', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="现居地址" name="nowAddress" labelWidth="85">
          <input placeholder="请输入现居住地址" :value="formData.nowAddress" @blur="binddata('nowAddress', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="户籍地址" name="censusAddress" labelWidth="85">
          <input placeholder="请输入户籍地址" :value="formData.censusAddress" @blur="binddata('censusAddress', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="行政区划" name="region" labelWidth="85">
          <input placeholder="请输入行政区划" :value="formData.region" @blur="binddata('region', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="航班号" name="flightNo" labelWidth="85">
          <input placeholder="请输入航班号" :value="formData.flightNo" @blur="binddata('flightNo', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="疫苗接种" name="isVaccine" labelWidth="85">
          <radio-group @change="binddata('isVaccine', $event.detail.value)">
            <label class="uni-list-cell uni-list-cell-pd"> <radio color="#2984F8" value="0" :checked="Number(formData.isVaccine) === 0" />已接种 </label>
            <label class="uni-list-cell uni-list-cell-pd"> <radio color="#2984F8" value="1" :checked="Number(formData.isVaccine) === 1" />未接种 </label>
          </radio-group>
        </uni-forms-item>
        <uni-forms-item label="性别" name="gender" labelWidth="85">
          <picker
            @change="handleListChange($event, 'gender', genderList, 'value')"
            :value="genderList.findIndex(g => g.value === formData.gender)"
            :range="genderList"
            range-key="label"
          >
            <text class="uni-input">{{ genderListMap[formData.gender] }}</text>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="出生日期" name="birthdate" labelWidth="85">
          <picker mode="date" :value="formData.birthdate" :start="startDate" :end="endDate" @change="binddata('birthdate', $event.detail.value)">
            <view class="uni-input">{{ formData.birthdate }}</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="籍贯" name="nativeAddress" labelWidth="85">
          <input placeholder="请输入籍贯" :value="formData.nativeAddress" @blur="binddata('nativeAddress', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="民族" name="nation" labelWidth="85">
          <picker @change="handleListChange($event, 'nation', nationList)" :value="nationList.findIndex(n => n === formData.nation)" :range="nationList">
            <text class="uni-input">{{ formData.nation }}</text>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="文化程度" name="education" labelWidth="85">
          <picker
            @change="handleListChange($event, 'education', educationList)"
            :value="educationList.findIndex(e => e === formData.education)"
            :range="educationList"
          >
            <text class="uni-input">{{ formData.education }}</text>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="婚姻状况" name="isMarried" labelWidth="85">
          <picker
            @change="handleListChange($event, 'isMarried', isMarriedList)"
            :value="isMarriedList.findIndex(m => m === formData.isMarried)"
            :range="isMarriedList"
          >
            <text class="uni-input">{{ formData.isMarried }}</text>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="职业" name="job" labelWidth="85">
          <input placeholder="请输入职业" :value="formData.job" @blur="binddata('job', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="工作单位" name="jobAddress" labelWidth="85">
          <input placeholder="请输入工作单位" :value="formData.jobAddress" @blur="binddata('jobAddress', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="联系人电话" name="relatedPhone" labelWidth="85">
          <input placeholder="请输入联系人电话" :value="formData.relatedPhone" @blur="binddata('relatedPhone', $event.detail.value)" />
        </uni-forms-item>
        <uni-forms-item label="隔离开始时间" name="startTime" labelWidth="85">
          <picker mode="date" :value="formData.startTime" :start="startDate" @change="binddata('startTime', $event.detail.value)">
            <view class="inner">
              <text :class="{'uni-input': true, 'placeholder': !formData.startTime}">{{ formData.startTime || '请选择隔离开始时间'}}</text>
            </view>  
          </picker>
        </uni-forms-item>
        <uni-forms-item label="隔离结束时间" name="endTime" labelWidth="85">
          <picker mode="date" :value="formData.endTime" :start="startDate" @change="binddata('endTime', $event.detail.value)">
            <view class="inner">
              <text :class="{'uni-input': true, 'placeholder': !formData.endTime}">{{ formData.endTime || '请选择隔离结束时间'}}</text>
            </view>  
          </picker>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="btn-row">
      <button class="primary" type="primary" :loading="btnLoading" @tap="handleSubmit">保存</button>
    </view>
  </view>
</template>
<script>
import mIcon from '@/components/m-icon/m-icon.vue';
import UserApi from '@/api/user';
import { baseUrl } from '@/common/request';
import { mapState, mapActions } from 'vuex';

export default {
  components: {
    mIcon
  },
  data() {
    const currentDate = this.getDate();
    return {
      btnLoading: false,
      avator: '',
      rules: {},
      // 表单数据
      formData: {
        idType: '',
        // 头像
        avator: '',
        // 姓名
        username: '',
        // 身份证
        idCard: '',
        // 手机号
        phone: '',
        // 现住址
        nowAddress: '',
        // 户籍
        censusAddress: '',
        // 行政区划
        region: '',
        // 航班号
        flightNo: '',
        // 籍贯
        nativeAddress: '',
        // 职业
        job: '',
        // 工作单位
        jobAddress: '',
        // 联系人电话
        relatedPhone: '',
        birthdate: currentDate,
        gender: 1,
        // 是否接种疫苗
        isVaccine: 0,
        // 民族
        nation: '汉族',
        // 教育程度
        education: '小学',
        // 婚姻状况
        isMarried: '未婚',
        // 隔离开始时间
        startTime: '',
        // 隔离结束时间
        endTime: ''
      },
      genderList: [
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        },
        {
          label: '未知',
          value: 9
        }
      ],
      nationList: ['汉族', '回族', '维吾尔族', '壮族', '其他少数民族'],
      educationList: ['小学', '初中', '高中/中专', '大专及以上', '不详'],
      isMarriedList: ['未婚', '已婚', '离异', '丧偶', '不详'],
      idTypeList: [
        // {
        //   id: 1,
        //   label: '身份证'
        // }
      ]
    };
  },
  computed: {
    ...mapState(['user']),
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate();
    },
    genderListMap() {
      return this.genderList.reduce(
        (pre, item) =>
          Object.assign(pre, {
            [item.value]: item.label
          }),
        {}
      );
    },
    idTypeListMap() {
      return this.idTypeList.reduce(
        (pre, item) =>
          Object.assign(pre, {
            [item.id]: item.label,
            [String(item.id)]: item.label
          }),
        {}
      );
    }
  },
  methods: {
    ...mapActions(['getUserInfo']),
    handleListChange($event, name, list, key) {
      const index = Number($event.detail.value);
      key ? this.binddata(name, list[index][key]) : this.binddata(name, list[index])
    },
    // 获取证件类型
    async getCondition() {
      const res = await this.$http.post(UserApi.getCondition);
      if (res) {
        const { idType } = res
        this.idTypeList = [].concat(idType);
        this.$set(this.formData, 'idType', this.idTypeList[0].id)
        console.log('idTypeList', this.idTypeList);
        console.log('idTypeListMap', this.idTypeListMap[this.formData.idType]);
      }
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    // 打开相机&相册
    startImage() {
      // // #ifdef H5
      // this.chooseImage();
      // // #endif

      // // #ifdef MP-WEIXIN
      // uni.authorize({
      //   scope: 'scope.camera',
      //   success: () => {
      //     this.chooseImage();
      //   },
      //   fail() {
      //     this.$toast('请开启微信相机拍照权限');
      //   }
      // });
      // #endif
    },
    // 选择图片上传
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: res => {
          this.uploadImage(res.tempFilePaths);
        }
      });
    },
    // 上传图片
    uploadImage(tempFilePaths) {
      uni.uploadFile({
        url: `${baseUrl}${UserApi.uploadAvator}`,
        filePath: tempFilePaths[0],
        name: 'file',
        formData: {
          token: uni.getStorageSync('token')
        },
        success: uploadFileRes => {
          // 上传成功
          console.log(uploadFileRes.data);
          // this.avator = ''
        }
      });
    },

    // 提交表单
    handleSubmit() {
      if (this.btnLoading) {
        return;
      }
      this.$refs.form.submit();
    },

    // 提交表单&校验
    submit(event) {
      const { errors, value } = event.detail;
      console.log('event', event);
      if (errors) return;
      this.save(value);
    },

    // 保存表单
    async save(value) {
      this.btnLoading = true;
      const res = await this.$http.post(UserApi.updateUserInfo, this.formData);

      console.log('value', this.formData);
      console.log('res', res);
      if (res) {
        this.$toast('保存成功');
      }

      await this.getUserInfo({ needLogin: false, showToast: false });
      this.btnLoading = false;
    }
  },
  async onShow() {
    uni.showLoading({
      title: '加载中...'
    });
    console.log('user', this.user);
    if (this.user) {
      Object.keys(this.user)
        .forEach(key => {
          if (!this.formData[key]) {
            this.$set(this.formData, key, this.user[key])
          }
        })
    }
    
    // this.formData = Object.assign(this.formData, this.user || {});
    await this.getCondition();
    uni.hideLoading();

  }
};
</script>
<style lang="scss">
.settings {
  width: 100%;
  padding: 0 40rpx;

  button {
    width: 100%;
  }

  .avator {
    height: 200rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f7fafd;

    .inner {
      position: relative;
    }

    .scan {
      position: absolute;
      right: 28rpx;
      bottom: 20rpx;
      color: $uni-color-primary;
      font-size: 48rpx;
    }

    img {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      // background-color: ;
    }
  }

  .uni-list-cell-pd {
    margin-right: 20rpx;

    .uni-radio-wrapper {
      margin-right: 20rpx;
    }
  }
  label {
    font-size: 26rpx;
  }
}
picker {
  .inner > text{
    // font-size: 34rpx;
    color: $uni-text-color-placeholder;
  }
}
</style>
